<template>
  <div>
    <!-- 头部 -->
    <div class="header">
      <div class="title">
        <span class="title-text">专利</span>
        <span class="title-count">{{ patentsMessage.total }}</span>
      </div>

      <div class="actions">
        <el-button type="primary" @click="upload">上 传</el-button>
        <el-button type="primary" @click="exportSelectedPapers">导 出</el-button>
      </div>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-container">
      <div class="filter-item">
        <span class="filter-label">授权公告日：</span>
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            class="custom-date-picker"
        />
      </div>

      <div class="filter-item">
        <span class="filter-label">个人排名：</span>
        <el-select
            v-model="params.authorRank"
            placeholder="请选择排名"
            clearable
            @change="handleRankChange"
            class="custom-select"
        >
          <el-option
              v-for="i in 13"
              :key="i"
              :label="`第${i}作者`"
              :value="i"
          />
        </el-select>
      </div>
    </div>

    <!-- 新增：选择全部按钮区域 -->
    <div class="select-all-container">
      <div v-if="!isAllSelected">
        <el-button type="primary" plain size="small" @click="selectAllData">
          选择全部数据
        </el-button>
        <span class="selection-info" v-if="selectedCount > 0">
          已选择 {{ selectedCount }} 条数据
        </span>
      </div>
      <div v-else>
        <el-button type="warning" plain size="small" @click="cancelSelectAll">
          取消选择全部
        </el-button>
        <span class="selection-info">已选择全部 {{ params.total }} 条数据</span>
      </div>
    </div>

    <div class="table-container">
      <el-table
          ref="patentTable"
          :data="patentsMessage.list"
          style="width: 100%"
          :cell-style="cellStyle"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @select-all="selectAllCurrentPage">
        <el-table-column
            type="selection"
            width="85"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="title"
            label="专利名称"
            width="240"
            align="center">
        </el-table-column>
        <el-table-column
            prop="patentType"
            width="110"
            label="专利类型"
            align="center">
        </el-table-column>
        <el-table-column
            prop="authorRank"
            width="100"
            label="个人排名"
            align="center">
        </el-table-column>
        <el-table-column
            prop="applicationDate"
            label="授权公告日"
            width="140"
            align="center">
        </el-table-column>
        <el-table-column
            label="操作"
            width="230"
            align="center">
          <template #default="scope">
            <el-button size="small" @click="download(scope.row)" :disabled="!scope.row.pdfPath">下载</el-button>
            <el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNo"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next"
        :total="params.total"
        class="pagination"
    />

    <patent-export v-model="showExportDialog" :papers="exportData" />
  </div>
</template>

<style scoped>
.header {
  height: 60px;
  width: 880px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.title {
  display: flex;
  align-items: center;
}

.title-text {
  font-weight: bold;
  font-size: 18px;
  margin-left: 20px;
}

.title-count {
  font-weight: bold;
  font-size: 18px;
  margin-left: 10px;
}

.actions {
  margin-right: 30px;
  display: flex;
  gap: 10px;
}

.custom-date-picker {
  width: 320px !important;
}

.custom-select {
  width: 160px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 20px;
  border-radius: 8px;
  margin: 10px 30px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-size: 14px;
  color: #606266;
}

.select-all-container {
  margin: 10px 30px;
  display: flex;
  align-items: center;
}

.selection-info {
  margin-left: 10px;
  color: #606266;
  font-size: 14px;
}

.table-container {
  width: 880px;
  overflow-y: auto;
  margin: 0 auto;
}

/* 根据是否有PDF设置鼠标指针样式 */
:deep(.el-table__row.has-pdf:hover>td) {
  cursor: pointer;
}

:deep(.el-table__row.no-pdf:hover>td) {
  cursor: default;
}

.pagination {
  margin-left: 10px;
  padding-bottom: 10px;
  margin-top: 20px;
}

.el-button--large {
  padding: 12px 20px;
  font-size: 16px;
  min-width: 120px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import {deletePatent, getPatent, getPatentsByIds} from "@/api/Manage/patent.js";
import {getPapersByIds} from "@/api/Manage/paper.js";
import PaperExport from "@/components/ExportDialog/paperExport.vue";
import PatentExport from "@/components/ExportDialog/patentExport.vue";
import { emit } from '@/utils/eventBus';
import {mergeImagesToPdf} from "@/api/Manage/File.js";

const router = useRouter();
const dateRange = ref(null);
const showExportDialog=ref(false)
const exportData = ref([]);
const patentTable= ref(null)
const patentsMessage = ref({
  list: [],
  total: 0
});

const params = reactive({
  isAsc: true,
  pageNo: 1,
  pageSize: 10,
  sortBy: 'id',
  startDate: "",
  endDate: "",
  total: 0,
  openid: "",
  authorRank: null
});

const selectedIds = ref([]);
const currentPageIds = computed(() => {
  return patentsMessage.value.list ? patentsMessage.value.list.map(item => item.id) : [];
});
const selectedCount = computed(() => selectedIds.value.length);
const needResetSelection = ref(false);
const isAllSelected = ref(false);

onMounted(() => {
  queryPatentsMessage();
});

watch(() => patentsMessage.value.list, (newVal) => {
  if (newVal && newVal.length > 0) {
    needResetSelection.value = true;
    nextTick(() => {
      if (needResetSelection.value) {
        setTableSelection();
        needResetSelection.value = false;
      }
    });
  }
}, { deep: true });

const gotoAddPatent = () => {
  router.push("/main/add/patents");
};

const queryPatentsMessage = async () => {
  try {
    const res = await getPatent(params);
    if (res.code === 1) {
      console.log("res.data", res.data);
      patentsMessage.value = res.data;
      params.total = res.data.total;

      const formatTimestamp = (timestamp) => {
        if (isNaN(timestamp)) {
          console.warn("Invalid timestamp:", timestamp);
          return null;
        }
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      if (Array.isArray(patentsMessage.value.list)) {
        patentsMessage.value.list.forEach(patent => {
          if (patent.applicationDate !== undefined) {
            patent.applicationDate = formatTimestamp(patent.applicationDate);
          } else {
            console.warn("applicationDate is undefined for patent:", patent);
          }
        });
      } else {
        console.warn("PatentsMessage.list is not an array:", patentsMessage.value.list);
      }

      console.log("Formatted PatentsMessage:", patentsMessage.value);
    } else {
      console.error("Request failed with code:", res.code);
    }
  } catch (error) {
    console.error("Request error:", error);
  }
};

const setTableSelection = () => {
  if (!patentTable.value) return;
  patentTable.value.clearSelection();

  if (isAllSelected.value) {
    setTimeout(() => {
      patentsMessage.value.list.forEach(row => {
        patentTable.value.toggleRowSelection(row, true);
      });
    }, 50);
    return;
  }

  setTimeout(() => {
    patentsMessage.value.list.forEach(row => {
      if (selectedIds.value.includes(row.id)) {
        patentTable.value.toggleRowSelection(row, true);
      }
    });
  }, 50);
};

const selectAllCurrentPage = (val) => {
  if (val) {
    currentPageIds.value.forEach(id => {
      if (!selectedIds.value.includes(id)) {
        selectedIds.value.push(id);
      }
    });
  } else {
    selectedIds.value = selectedIds.value.filter(id => !currentPageIds.value.includes(id));
  }
};

const selectAllData = async () => {
  try {
    await ElMessageBox.confirm(
        `确定要选择全部${params.total}条数据吗？`,
        '选择全部数据',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
    );

    isAllSelected.value = true;
    if (patentTable.value) {
      patentsMessage.value.list.forEach(row => {
        patentTable.value.toggleRowSelection(row, true);
      });
    }

    ElMessage.success(`已选择全部${params.total}条数据`);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('选择全部数据失败');
      console.error('选择全部数据失败:', error);
    }
  }
};

const cancelSelectAll = () => {
  isAllSelected.value = false;
  selectedIds.value = [];
  if (patentTable.value) {
    patentTable.value.clearSelection();
  }
  ElMessage.info('已取消选择全部数据');
};

const download = async (row) => {
  // 显示加载状态，因为合并PDF可能需要一定时间
  const loading = ElLoading.service({
    lock: true,
    text: '正在生成PDF文件，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {

    const response = await mergeImagesToPdf(row.pdfPath);

    // 处理返回的文件流
    const blob = new Blob([response.data], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);

    // 创建下载链接
    const a = document.createElement('a');
    a.href = url;
    // 使用项目名称作为文件名
    a.download = `${row.title || '合并文件'}.pdf`;
    document.body.appendChild(a);
    a.click();

    // 清理资源
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);

    ElMessage.success('PDF生成并下载成功');
  } catch (error) {
    console.error('下载失败:', error);
    // 根据错误信息显示更具体的提示
    if (error.response && error.response.status === 404) {
      ElMessage.error('文件不存在');
    } else if (error.response && error.response.status === 400) {
      ElMessage.error('无效的文件路径');
    } else {
      ElMessage.error('生成PDF失败，请稍后重试');
    }
  } finally {
    // 无论成功失败都关闭加载状态
    loading.close();
  }
};

const upload = () => {
  router.push("/main/add/patents");
};

const edit = (row) => {
  router.push({ path: '/main/edit/patents', query: { id: row.id } });
  console.log('编辑:', row);
};

const remove = async (row) => {
  try {
    await ElMessageBox.confirm('您确定删除吗？', '确认删除', { type: "warning" });
    const res = await deletePatent(row.id);
    if (res.code === 1) {
      ElMessage.success('操作成功');
      selectedIds.value = selectedIds.value.filter(id => id !== row.id);
      await queryPatentsMessage();
      emit('refresh-counts');
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("Delete error:", error);
    }
  }
};

const handleRowClick = (row, column, event) => {
  // 检查是否点击的是操作列（避免与操作按钮冲突）
  if (column.label === '操作') {
    return;
  }

  // 如果有PDF路径，则触发下载
  if (row.pdfPath) {
    previewPdf(row);
  }
};

const previewPdf = (row) => {
  if (!row.pdfPath) {
    ElMessage.warning('该论文暂无PDF文件');
    return;
  }

  router.push({
    path: '/preview',
    query: {
      pdfUrl: encodeURIComponent(row.pdfPath),
      title: encodeURIComponent(row.title),
      type: 'patent', // 添加类型参数
      id: row.id, // 添加ID参数
    }
  });
};
const handleSelectionChange = (selection) => {
  if (isAllSelected.value) return;
  const currentSelectedIds = selection.map(item => item.id);
  const unselectedIds = currentPageIds.value.filter(id => !currentSelectedIds.includes(id));
  selectedIds.value = selectedIds.value.filter(id => !unselectedIds.includes(id));
  currentSelectedIds.forEach(id => {
    if (!selectedIds.value.includes(id)) {
      selectedIds.value.push(id);
    }
  });
};

const handleSizeChange = (pageSize) => {
  params.pageSize = pageSize;
  queryPatentsMessage();
};

const handleCurrentChange = (pageNum) => {
  params.pageNo = pageNum;
  queryPatentsMessage();
};

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  return { padding: '15px' };
};

const tableRowClassName = ({ row }) => {
  return row.pdfPath ? 'has-pdf' : 'no-pdf';
};

const handleDateChange = (val) => {
  if (val) {
    params.startDate = val[0];
    params.endDate = val[1];
  } else {
    params.startDate = "";
    params.endDate = "";
  }
  params.pageNo = 1;
  selectedIds.value = [];
  isAllSelected.value = false;
  queryPatentsMessage();
};

const handleRankChange = (val) => {
  params.pageNo = 1;
  selectedIds.value = [];
  isAllSelected.value = false;
  queryPatentsMessage();
};

const batchExportData = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在导出数据，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const queryParams = {
      isAsc: params.isAsc,
      sortBy: params.sortBy,
      startDate: params.startDate,
      endDate: params.endDate,
      authorRank: params.authorRank,
      pageSize: 50,
      pageNo: 1
    };

    const firstBatchRes = await getPatent(queryParams);
    if (firstBatchRes.code !== 1 || !firstBatchRes.data) {
      throw new Error('获取数据失败');
    }

    const total = firstBatchRes.data.total;
    const totalPages = Math.ceil(total / queryParams.pageSize);
    let allData = [...firstBatchRes.data.list];

    for (let page = 2; page <= totalPages; page++) {
      queryParams.pageNo = page;
      const res = await getPatent(queryParams);
      if (res.code === 1 && res.data && Array.isArray(res.data.list)) {
        allData = [...allData, ...res.data.list];
      }
    }

    exportData.value = allData;
    showExportDialog.value = true;
    loadingInstance.close();
    return allData;
  } catch (error) {
    loadingInstance.close();
    ElMessage.error('导出失败: ' + error.message);
    throw error;
  }
};

const exportSelectedPapers = async () => {
  if (!isAllSelected.value && selectedIds.value.length === 0) {
    ElMessage.warning('请选择要导出的专利');
    return;
  }

  try {
    if (isAllSelected.value) {
      await batchExportData();
    } else {
      const res = await getPatentsByIds(selectedIds.value);
      if (res.code === 1 && res.data) {
        showExportDialog.value = true;
        exportData.value = res.data;
      } else {
        ElMessage.error('获取专利数据失败');
      }
    }
  } catch (error) {
    console.error("导出数据失败:", error);
    ElMessage.error('导出失败');
  }
};
</script>
